from itsdangerous import TimedJSONWebSignatureSerializer as Serializer,BadData
from django.conf import settings



def generate_save_user_token(openid):
    # 添加密钥
    serializer = Serializer(settings.SECRET_KEY, 300)

    # 添加openid
    data = {
        "openid": openid
    }
    # 是一个byes数据
    token = serializer.dumps(data)

    return token.decode()


def check_save_user_token(access_token):
    #解密 获得openid

    #创建itsdangerous对象
    serializer = Serializer(settings.SECRET_KEY, 300)
    #解密
    try:
        data=serializer.loads(access_token)
    except BadData:
        #如果解密失败badData会抛出异常
        return None
    else:
        #返回access_token中的openid
        return data["openid"]
